from typing import Optional

from fastapi import HTTPException

from src.database.models import User
from src.user_service.schemas import (
    Auth_record,
    Registration_form,
    Login_form,
    My_account
)

from src.database.my_crud import My_crud
from src.security_module import pwd_context


user_crud = My_crud(User)


async def raise_401_error(user_id: Optional[int]):
    pass


class Auth_service:

    async def login_user(
        self,
        payload: Login_form,
        user_id: Optional[int]
    ):
        if user_id and user_id > 0:
            if await user_crud.exist([User.id == user_id]):
                return user_id

        user_data = await user_crud.get(
            [User.email == payload.email],
            Auth_record,
        )

        if (
            user_data is None or
            not (pwd_context.verify(payload.password, user_data.password))
        ):
            raise HTTPException(
                status_code=401,
                detail="Wrong email or password"
            )

        return user_data.id

    async def create_user(
            self,
            payload: Registration_form,
            user_id: Optional[int]
    ):
        if user_id is not None and user_crud.exist([User.id == user_id]):
            raise HTTPException(
                status_code=403,
                detail="authorized user"
            )
        if await user_crud.exist([User.email == payload.email]):
            raise HTTPException(
                status_code=409,
                detail="user with same email exists"
            )

        record = Auth_record(
            firstName=payload.firstName,
            lastName=payload.lastName,
            email=payload.email,
            password=pwd_context.hash(payload.password)
        )

        user_record = await user_crud.create(
            record,
            Output_model=My_account
        )

        return user_record
